<?php

namespace FrontEnd\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use FrontEnd\Model\FrontEnd;
use Zend\Filter\File\RenameUpload;
use Zend\Paginator\Paginator;
use Zend\Paginator\Adapter\Null as PageNull;

use Zend\Validator\File\Size;
use Zend\Validator\File\IsImage;
use Zend\Validator\File\MimeType;
use Zend\Form\Element;
use Zend\Validator\File\Count;
use Zend\Math\Rand;
use Zend\View\View;

use Imagine\Gd\Imagine;

class IndexController extends HeadController
{
	protected $ProductTable;
	protected $Imagine;
	protected $ProductTypeTable;
	
    public function indexAction()
    {	
    	$this -> headsAction();    	
    	$this->layout('layout/frontend');

    	/* $arrdf=pathinfo('img.v3.news.zdn.vn/w660/Uploaded/xpcwvovb/2015_03_16/danhnhau2.jpg');
    	var_dump($arrdf['extension']); */
    	/* $request = $this->getRequest();
    	$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
    	$form = new ProductForm(null,$dbAdapter);
    	$form->setInputFilter(new ProductFilter($dbAdapter) );
    	if($request->isPost()){
    		$data = $request->getPost();
    		$this->redirect()->toUrl('/product/search_by/'.$data->nameprosearch);
    	}
    	$search = $this->params()->fromRoute('search_by'); */
    	
    	$search = $this->params()->fromRoute('search_by');
    	$itemsPerPage = 10;
    	$pageRange = 5;
    	$page = $this->params()->fromRoute('page', 1);
    	$offset = ($page - 1) * $itemsPerPage;
    	
    	$urlhientai = $this->request->getRequestUri();
    	$mahoa = md5($urlhientai);
    	if(!empty($search)){
    		$listproduct = $this->getProductTable()->fetchSearchAll($offset, $itemsPerPage,$search,$mahoa);
    	}else {
    		$allRecord = $this->getProductTable()->countAll();
    		$listproduct = $this->getProductTable()->fetchAllFronend();   		
    		$listproduct1 = $this->getProductTable()->fetchAllFronend1($offset, $itemsPerPage,$mahoa);
    		$listproductvideo = $this->getProductTable()->fetchAllFronendvideohot();
    		$listproducttruyenhot = $this->getProductTable()->fetchAllFronendtruyenhot();
    	}
    		
    	foreach ($listproduct as $val)
    		$this->imageAction(UPLOAD_PATH.'/product/'.$val['LINKIMG'],$val['LINKIMG'],190,134);
    	foreach ($listproduct1 as $val)
    		$this->imageAction(UPLOAD_PATH.'/product/'.$val['LINKIMG'],$val['LINKIMG'],696,340);
    	foreach ($listproductvideo as $val)
    		$this->imageAction(UPLOAD_PATH.'/product/'.$val['LINKIMG'],$val['LINKIMG'],126,83);
    	foreach ($listproducttruyenhot as $val)
    		$this->imageAction(UPLOAD_PATH.'/product/'.$val['LINKIMG'],$val['LINKIMG'],126,83);
    	
    	$pageNull = new PageNull($allRecord);
    	$paginator = new Paginator($pageNull);
    	$paginator->setCurrentPageNumber($page);
    	$paginator->setItemCountPerPage($itemsPerPage);
    	$paginator->setPageRange($pageRange);
    	
        return new ViewModel(array(
                'productfrontend' => $listproduct,
        		'productfrontend1' => $listproduct1,
        		'productfrontendvideo' => $listproductvideo,
        		'productfrontendtruyenhot' => $listproducttruyenhot,
        		'paginator' => $paginator,
         ));
        
    }
        
    public function videoAction(){
    	$this -> headsAction();
    	$this->layout('layout/frontend');
    	$id = (int) $this->params()->fromRoute('id', 0);
    	 
    	if (!$id) {
    		return $this->notFoundAction ();
    	}else{
    		$product = $this->getProductTable ()->getProduct ( $id );
    		$productcl = $this->getProductTable ()->cungloai ( $id );
    		$this -> headsAction($product->NAME_PR);
    		if(empty($product) || empty($productcl)){
    			return $this->notFoundAction ();
    		}else{
    			$urlhientai = $this->request->getRequestUri();
    			$url = '/video/'.$id.'-'.$this->vn2latin($product->NAME_PR,true).'.html';
    			if($urlhientai != $url)
    				$this->redirect()->toUrl($url);
    			
    			foreach ($productcl as $val)
    				$this->imageAction(UPLOAD_PATH.'/product/'.$val['LINKIMG'],$val['LINKIMG'],126,83);
    			
    			return new ViewModel(array(
    					'Product_detail' => $product,
    					'productcl' => $productcl,
    			));
    		}
    		
    		
    	}
    	
    }
    
    public function typeAction(){
    	$this -> headsAction();
    	$this->layout('layout/frontend');
    	$id = (int) $this->params()->fromRoute('id', 0);
    
    	if (!$id) {
    		return $this->notFoundAction ();
    	}else{
    		$producttype = $this->getProductTypeTable ()->getProductType ( $id );
    		$producttypes = $this->getProductTable ()->types ( $id );
    		$listproducthot = $this->getProductTable()->fetchAllFronendtypehot($id);
    		
    		$this -> headsAction($producttype->NAME_PRT);
    		if(empty($producttype) || empty($listproducthot)){
    			return $this->notFoundAction ();
    		}else{
    			$this -> headsAction($producttype->NAME_PRT);
    			$urlhientai = $this->request->getRequestUri();
    			$url = '/type/'.$id.'-'.$this->vn2latin($producttype->NAME_PRT,true).'.html';
    			if($urlhientai != $url)
    				$this->redirect()->toUrl($url);
    			 
    			foreach ($producttypes as $val)
    				$this->imageAction(UPLOAD_PATH.'/product/'.$val['LINKIMG'],$val['LINKIMG'],696,340);
    			foreach ($listproducthot as $val)
    				$this->imageAction(UPLOAD_PATH.'/product/'.$val['LINKIMG'],$val['LINKIMG'],126,83);
    			
    			return new ViewModel(array(
    					'producttypes' => $producttypes,
    					'listproducthot' => $listproducthot,
    					'hot' =>$producttype->NAME_PRT
    			));
    		}
    
    
    	}
    	 
    }
    
    public function imageAction($destinationPath,$timthumb,$width, $height)
    {
    	$imagine = $this->getImagineService();
    	$size = new \Imagine\Image\Box($width, $height);
    	$mode = \Imagine\Image\ImageInterface::FILTER_UNDEFINED;
    
    	$image = $imagine->open($destinationPath);
    	$structure = APPLICATION_PATH.'/timthumb/'.$width.'x'.$height;
    	if (!is_dir($structure))
    	   mkdir($structure, 0777, true);
    	$image->resize($size, $mode)->save($structure.'/'.$timthumb);
    }

    public function getProductTable()
    {
    	if (!$this->ProductTable) {
    		$sm = $this->getServiceLocator();
    		$this->ProductTable = $sm->get('Product\Model\ProductTable');
    	}
    	return $this->ProductTable;
    }
    
    public function getImagineService()
    {
    	if ($this->Imagine === null)
    	{
    		$this->Imagine = $this->getServiceLocator()->get('image_service');
    	}
    	return $this->Imagine;
    }
    
    public function getProductTypeTable()
    {
    	if (!$this->ProductTypeTable) {
    		$sm = $this->getServiceLocator();
    		$this->ProductTypeTable = $sm->get('ProductType\Model\ProductTypeTable');
    	}
    	return $this->ProductTypeTable;
    }
    /* định dạng chuỗi nhập
     tham số $tolower, true nếu bạn muốn nhận chuỗi không dấu dưới dạng viết thường,
     false sẽ trả về chữ không dấu còn viết hoa hay viết thường thì duy trì như chuỗi ban đầu đưa vào. */
function vn2latin($str, $tolower = false)
    {
    		$str = preg_replace("/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/", 'a', $str);
			$str = preg_replace("/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/", 'e', $str);
			$str = preg_replace("/(ì|í|ị|ỉ|ĩ)/", 'i', $str);
			$str = preg_replace("/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/", 'o', $str);
			$str = preg_replace("/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/", 'u', $str);
			$str = preg_replace("/(ỳ|ý|ỵ|ỷ|ỹ)/", 'y', $str);
			$str = preg_replace("/(đ)/", 'd', $str);
			$str = preg_replace("/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/", 'A', $str);
			$str = preg_replace("/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/", 'E', $str);
			$str = preg_replace("/(Ì|Í|Ị|Ỉ|Ĩ)/", 'I', $str);
			$str = preg_replace("/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/", 'O', $str);
			$str = preg_replace("/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/", 'U', $str);
			$str = preg_replace("/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/", 'Y', $str);
			$str = preg_replace("/(Đ)/", 'D', $str);
		   $str = preg_replace(array('/[^a-zA-Z0-9 -]/', '/[ -]+/', '/^-|-$/'),
		   		array('', '-', ''), $str);
    	if ($tolower) {
    		return strtolower($str);
    	}
    
    	return $str;
    
    }
}
